package org.juiceshop.gm.midi;

import java.util.ArrayList;
import java.util.List;


public class SequenceBuilderX {

	public static final int RESOLUTION = 256/4;
	public static final int WHOLE = RESOLUTION * 4;

	private MidiSequence _sequence;
	private List<TrackBuilderX> _trackBuilders;
	
	public SequenceBuilderX() {
		_sequence = new MidiSequence(RESOLUTION);
		_trackBuilders = new ArrayList<TrackBuilderX>();
	}
	
	public MidiSequence getSequence() {
		return _sequence;
	}
			
	public TrackBuilderX getTrackBuilder (int trackNum) {
		assert trackNum>=0 && trackNum<16;
		while (_trackBuilders.size()<=trackNum) {
			int n = _trackBuilders.size();
			TrackBuilderX tbuilder = new TrackBuilderX(_sequence,n);
			_trackBuilders.add(tbuilder);
		}
		return _trackBuilders.get(trackNum);
	}
	
	public long getMaxTicks() {
		long maxTicks = 0l;
		for (TrackBuilderX tb : _trackBuilders) {
			if (tb.getTimer()>maxTicks) maxTicks = tb.getTimer();
		}
		return maxTicks;
	}
	
	public long sync() {
		long maxTicks = getMaxTicks();
		for (TrackBuilderX tb : _trackBuilders) {
			tb.setTimer(maxTicks);
		}
		return maxTicks;
	}
	
	public void tempo (int bpm) {
        if (bpm<1) {
            throw new IllegalArgumentException("Invalid BPM value: "+bpm);
        }
        long ticks = sync();
        _sequence.addTempoEvent(ticks, bpm);
    }

	public void close() {
		long maxTicks = sync();
		_sequence.addEndOfTrackEvent(maxTicks);
	}
	
	
	public static long calculateTicks(double duration) {
        return Double.valueOf(WHOLE * duration).longValue();
    }

	
}


